package com.wpx.log.core.aspect;

import java.lang.reflect.Field;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;
import com.wpx.log.core.exception.DoHandlerException;
import com.wpx.log.core.handler.ILogHandler;
import com.wpx.log.core.module.Entry;


public class DoHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(DoHandler.class);
	
	@Autowired
	private LogContext logContext;


	public  void doAsyncLogHandler(LogRequestContext requestContext, Object logObj) {
		List<Entry<Field, ILogHandler>> handlers = this.logContext.getLogHandlers(true);
		doLogHandler(handlers, requestContext, logObj);	
	}
	
	@Async
	public  void doLogHandler(LogRequestContext requestContext, Object logObj) {
		List<Entry<Field, ILogHandler>> handlers = this.logContext.getLogHandlers(false);
		doLogHandler(handlers, requestContext, logObj);	
		if(logContext.isDebug()) {
			logger.info("\n"+this.getClass().getName()+" = "+ logObj);
		}
		this.logContext.getLogservice().saveLog(logObj);
	}
	
	private void doLogHandler(List<Entry<Field, ILogHandler>> handlers,LogRequestContext requestContext, Object logObj) {
		for (Entry<Field, ILogHandler> entry : handlers) {
			try {
				Field field = entry.getKey();
				Object value = entry.getValue().handler(logContext, requestContext, field);
				field.set(logObj, value);
			} catch (Exception e) {
				e.printStackTrace();
				throw new DoHandlerException("执行logHandler异常！", e);
				
			}
		}
	}
}
